﻿using UnityEngine;
using System.Collections;

public class swipeScript : MonoBehaviour {

	private Vector3 firstPos;
	private Vector3 lastPos;
	private float swipeDist;
	bool playerAlive;

	public float power;
	public float ymax;
	public float xmax;
	private Vector3 playerPos;
	private float factor=34f;

	public GameObject platforms;
	public GameObject items;
	
	public bool isFirstTouch = false;

	// Use this for initialization
	void Start () {
		swipeDist = Screen.height * 0.2f;
		Physics.gravity = new Vector3 (0,-20,0);
		playerPos = transform.position;
		playerAlive = true;
	}

	public void CreateAndDestroyPlatforms()
	{
		platforms.GetComponent<PlatformScript> ().CreateAndDestroy (platforms);
		//items.GetComponent<ItemScript>().CreateAndDestroy(items);
	}
	
	// Update is called once per frame
	void Update () {
	
		if (playerAlive) {
			playerLogic ();
		}
			else {
				Application.Quit();
			}
		}

	void playerLogic ()
	{
		//check touch input

		foreach (Touch t in Input.touches) 
		{
			if(t.phase==TouchPhase.Began)
			{
				firstPos=t.position;
				lastPos=t.position;
			}

			if (t.phase == TouchPhase.Ended)
			{
				lastPos = t.position;
				//First check if it's actually a drag
				
				if (Mathf.Abs(lastPos.x - firstPos.x) > swipeDist || Mathf.Abs(lastPos.y - firstPos.y) > swipeDist)
				{   //It's a drag
					
					//x and y repesent force to be added in the x, y axes.
					float x = (lastPos.x - firstPos.x) / Screen.height * factor;
					if(lastPos.x < firstPos.x && x < -(xmax))
					{
						x = -(xmax);
					}
					else if(lastPos.x > firstPos.x && x > xmax)
					{
						x = xmax;
					}
					//Debug.Log(x);

					float y = (lastPos.y - firstPos.y) / Screen.height * factor;
					if (y>ymax)
					{
						y = ymax;
					}
					//Debug.Log(y);
					//Now check what direction the drag was
					//First check which axis
					if (Mathf.Abs(lastPos.x - firstPos.x) > Mathf.Abs(lastPos.y - firstPos.y))
					{   //If the horizontal movement is greater than the vertical movement...
						
						if (lastPos.x>firstPos.x)  //If the movement was to the right)
						{   //Right move
		
							rigidbody2D.AddForce((new Vector3(x,10,15))*power);
							isFirstTouch = true;
						}
						else
						{   //Left move
							rigidbody2D.AddForce((new Vector3(x,10,15))*power);
							isFirstTouch = true;

						}
					}
					else
					{   //the vertical movement is greater than the horizontal movement
						if (lastPos.y>firstPos.y)  //If the movement was up
						{   //Up move
							rigidbody2D.AddForce((new Vector3(x,y,15))*power);
							isFirstTouch = true;

						}
					}
				}
			}
  		}

		if (isFirstTouch) {
			CreateAndDestroyPlatforms();
		}
 	}
}